package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicHosptype;
import com.hsnn.medstgmini.base.dict.service.DicHosptypeManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 医疗机构类别字典
 * @author jingyu
 * @date 2015-6-8
 */
@Controller
@RequestMapping("/dict")
public class DicHosptypeController {
	
	private static final Logger log = Logger.getLogger(DicHosptypeController.class);
	
	@Autowired
	private DicHosptypeManager dicHosptypeManager;
	
	@Autowired
	private HttpServletRequest request;
	/**
	 * @category 进入列表页面
	 * @return 医疗机构类别字典列表页面
	 */
	@RequestMapping("/dicHosptypeList")
	public String dicHosptypeList() {
		return "/base/dict/hosptypeList";
	}
	/**
	 * @category 分页获取医疗机构类别字典json
	 * @param result 分页参数
	 * @param instance 查询条件 code，name
	 * @return 医疗机构类别分页json
	 */
	@RequestMapping("querydicHosptypeListJson")
	@ResponseBody
	public Pagination querydicHosptypeList() {
		printParams();
		Pagination page = new Pagination(request);
		if(StringUtils.isNotBlank(request.getParameter("hospTypeCode"))){
			page.getConditions().put("hospTypeCode", request.getParameter("hospTypeCode").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("hospType"))){
			page.getConditions().put("hospType", request.getParameter("hospType").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("status"))){
			page.getConditions().put("status", request.getParameter("status").trim());
		}
		try {
			dicHosptypeManager.getDicHospTypeList(page);
		} catch (Exception e) {
			e.printStackTrace();
		} catch(Error error) {
			error.printStackTrace();
		}
		return page;
	}
	
	/**
	 * @category 进入维护记录列表页面
	 * @param model
	 * @param tid
	 * @return 医疗机构类别维护记录列表页面
	 */
	@RequestMapping("/log")
	public String dicHosptypeLog(Model model,String tid) {
		printParams();
		model.addAttribute("tid",tid);
		request.setAttribute("hospTypeCode", request.getParameter("hospTypeCode"));
		try {
			String hospType = new String(request.getParameter("hospType").getBytes("ISO8859-1"), "utf-8");
			request.setAttribute("hospType", hospType);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/base/dict/hosptypeLog";
	}
	/**
	 * @category 分页获取维护记录列表json
	 * @param result
	 * @param tid
	 * @param startTime
	 * @param endTime
	 * @return 维护记录查询结果json
	 */
	@RequestMapping("querydicHosptypeLogJson")
	@ResponseBody
	public Pagination querydicHosptypeLogJson() {
		printParams();
		Pagination page = new Pagination(request);
		page.getConditions().put("hospTypeId", request.getParameter("tid"));
		if(StringUtils.isNotBlank(request.getParameter("startTime"))){
			page.getConditions().put("startTime", request.getParameter("startTime").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("endTime"))){
			page.getConditions().put("endTime", request.getParameter("endTime").trim());
		}
		try {
			dicHosptypeManager.getDicHospTypeLogList(page);
		} catch (Exception e) {
			e.printStackTrace();
		} catch(Error error) {
			error.printStackTrace();
		}
		return page;
	}
	
	/**
	 * 基础库 数据字典 医疗机构类别字典 根据id查询 医疗机构类别 日志详情
	 * @param page
	 * @return
	 */
	@RequestMapping("/toDicHosptypeLogDetail")
	public String toDicHosptypeLogDetail(){
		printParams();
		log.info("enter toDicHosptypeLogDetail method!");
		Pagination  page = new Pagination();
		page.getConditions().put("logId", request.getParameter("logId"));
		List<Map<String,Object>> list = dicHosptypeManager.getDicHosptypeLogDetail(page);
		request.setAttribute("list", list);
		return "/base/dict/hosptypeLogDetail";
		
	}
	
	
	/**
	 * 
	 *@category 批量启用停用
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicHosptype>>() {
				}.getType();
				List<DicHosptype> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (DicHosptype dds : list) {
						dds.setUpdUser(user.getId());
						dicHosptypeManager.changeStatus(dds);
					}
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * 
	 *@category 查询编辑数据
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("initEdit")
	@ResponseBody
	public Pagination initEdit() {
		printParams();
		Pagination page = new Pagination();
		if(StringUtils.isNotBlank(request.getParameter("hospTypeId"))){
			page.getConditions().put("hospTypeId", request.getParameter("hospTypeId").trim());
		}
		try {
			page = dicHosptypeManager.initEdit(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 新增或编辑医院类别
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping(value={"/add","/edit","/addTwo"})
	@ResponseBody
	public Pagination dicHosptypeUpdate() {
		printParams();
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		page.getConditions().put("updUser", user.getId());
		if(StringUtils.isNotBlank(request.getParameter("hospTypeCode"))){
			page.getConditions().put("hospTypeCode", request.getParameter("hospTypeCode").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("hospType"))){
			page.getConditions().put("hospType", request.getParameter("hospType").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("hospTypeId"))){
			page.getConditions().put("hospTypeId", request.getParameter("hospTypeId").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("fatherId"))){
			page.getConditions().put("fatherId", request.getParameter("fatherId").trim());
		}else{
			page.getConditions().put("fatherId", "0");
		}
		try {
			if(request.getParameter("hospTypeId")!=null){
				if(StringUtils.isNotBlank(request.getParameter("hospTypeId"))){
					//update
					if(StringUtils.isNotBlank(request.getParameter("hospTypeCode"))){
		            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type_code",request.getParameter("hospTypeCode").trim(),request.getParameter("hospTypeId"));
		            	 if(list.size()>0){
		            		 page.setMsg("医疗机构类别编码已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入医疗机构类别编码!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            if(StringUtils.isNotBlank(request.getParameter("hospType").trim())){
		            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type",request.getParameter("hospType").trim(),request.getParameter("hospTypeId"));
		            	 if(list.size()>0){
		            		 page.setMsg("医疗机构类别名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入医疗机构类别名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
					dicHosptypeManager.updateHospType(page);
					page.setMsg("修改成功!");
					page.setSuccess(true);
				}else{
					//add
					if(StringUtils.isNotBlank(request.getParameter("hospTypeCode"))){
		            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type_code",request.getParameter("hospTypeCode").trim(),"");
		            	 if(list.size()>0){
		            		 page.setMsg("医疗机构类别编码已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入医疗机构类别编码!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            if(StringUtils.isNotBlank(request.getParameter("hospType").trim())){
		            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type",request.getParameter("hospType").trim(),"");
		            	 if(list.size()>0){
		            		 page.setMsg("医疗机构类别名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入医疗类别名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            String hospTypeAddId = UUID.randomUUID().toString();
		            page.getConditions().put("hospTypeAddId", hospTypeAddId);
		            if(!"0".equals(request.getParameter("fatherId"))){
		            	dicHosptypeManager.addHospType(page);
						page.setMsg("保存成功!");
						page.setSuccess(true);
		            }else{
		            	if(StringUtils.isNotBlank(request.getParameter("fhospTypeCode"))){
		            		page.getConditions().put("hospTypeCode", request.getParameter("fhospTypeCode").trim());
		            		page.getConditions().put("hospType", request.getParameter("fhospType").trim());
		            		dicHosptypeManager.addHospType(page);
		            		page.getConditions().put("hospTypeCode", request.getParameter("hospTypeCode").trim());
		            		page.getConditions().put("hospType", request.getParameter("hospType").trim());
		            		page.getConditions().put("hospTypeAddId", UUID.randomUUID().toString());
		            		page.getConditions().put("fatherId", hospTypeAddId);
		            		dicHosptypeManager.addHospType(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}else{
		            		dicHosptypeManager.addHospType(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}
		            }
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg("保存失败!");
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 检查是否重复
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("checkRepeat")
	@ResponseBody
	public Pagination checkRepeat() {
		printParams();
		Pagination page = new Pagination();
		String hospTypeCode = request.getParameter("hospTypeCode");
		String hospType = request.getParameter("hospType");
		
		try {
			 if(StringUtils.isNotBlank(hospTypeCode)){
	            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type_code",hospTypeCode.trim(),"");
	            	 if(list.size()>0){
	            		 page.setMsg("医疗机构类别编码已存在!");
	            		 page.setSuccess(false);
	            		 return page;
	                 }else{
	                	 page.setSuccess(true);
	                 }
	            }else{
	            	page.setMsg("请输入医疗机构类别编码!");
	            	page.setSuccess(false);
	            	return page;
	            }
	            if(StringUtils.isNotBlank(hospType)){
	            	List<DicHosptype> list=dicHosptypeManager.getHospTypeBy("hosp_type",hospType.trim(),"");
	            	 if(list.size()>0){
	            		 page.setMsg("医疗机构类别名称已存在!");
	            		 page.setSuccess(false);
	            		 return page;
	                 }else{
	                	 page.setSuccess(true);
	                 }
	            }else{
	            	page.setMsg("请输入医疗类别名称!");
	            	page.setSuccess(false);
	            	return page;
	            }
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg(e.toString());
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String hospTypeCode = request.getParameter("hospTypeCode");
		String hospType = request.getParameter("hospType");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(hospTypeCode)){
			page.getConditions().put("hospTypeCode", hospTypeCode.trim());
		}
		if(StringUtils.isNotBlank(hospType)){
			page.getConditions().put("hospType", hospType.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 dicHosptypeManager.getDicHospTypeNoPage(page);
			 String title = "医疗机构类别";
			 String[] headers = {"一级编码","一级名称","二级编码","二级名称","状态"};
			 String[] alias = {"fatherHospTypeCode","fatherHospType","hospTypeCode","hospType","status"};
			 ExcelUtil.exportExcel(page, os, title, headers, alias);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
